package com.contactbook.web.controller.contact;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.contactbook.web.service.ContactClient;

import contactbook.model.Account;
import contactbook.model.Contact;

public class InfoContactController extends HttpServlet implements Servlet {

	private static final long serialVersionUID = 1L;
	
	private ContactClient contactClient;
	
	public InfoContactController() {
		super();
		contactClient = new ContactClient();
	}
	
	public void init() throws ServletException {
    	super.init();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		RequestDispatcher dispatcher = request.getRequestDispatcher("/Index");
		dispatcher.forward(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession(true);
		Account account = (Account)session.getAttribute("account");
		RequestDispatcher dispatcher = request.getRequestDispatcher("/Index");;
	
		if (account != null) {
			contactClient.login(account.getLogin(), account.getPassword());
			
			int contactId = Integer.valueOf(request.getParameter("contactId"));
			Contact contact = contactClient.getContactById(contactId);
			request.setAttribute("contact", contact);
			dispatcher = request.getRequestDispatcher("/infoContact.jsp");
			
			contactClient.logout();
		}
		dispatcher.forward(request, response);
	}
	
	public void destroy() {
		super.destroy();
	}
	
}
